/**
 * 小程序构建脚本
 * 用于构建生产环境代码
 */

const path = require('path');
const webpack = require('webpack');
const { merge } = require('webpack-merge');
const chalk = require('chalk');
const { BundleAnalyzerPlugin } = require('webpack-bundle-analyzer');
const FileManagerPlugin = require('filemanager-webpack-plugin');
const baseConfig = require('../config/webpack.config');

// 获取命令行参数
const analyze = process.env.ANALYZE === 'true';

// 合并配置
const buildConfig = merge(baseConfig, {
  // 设置为生产模式
  mode: 'production',
  
  // 生产环境优化
  optimization: {
    minimize: true,
  },
  
  // 生产环境插件
  plugins: [
    // 定义环境变量
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('production')
    }),
    
    // 打包完成后创建ZIP文件
    new FileManagerPlugin({
      events: {
        onEnd: {
          archive: [
            {
              source: path.resolve(__dirname, '../dist'),
              destination: path.resolve(__dirname, '../dist/miniprogram.zip'),
              format: 'zip',
            },
          ],
        },
      },
    }),
  ],
});

// 添加分析插件
if (analyze) {
  buildConfig.plugins.push(
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      reportFilename: 'report.html',
      openAnalyzer: true
    })
  );
}

// 执行构建
console.log(chalk.blue('🚀 开始构建生产环境代码...\n'));

const compiler = webpack(buildConfig);

compiler.run((err, stats) => {
  if (err) {
    console.error(chalk.red('❌ 构建失败:'), err);
    process.exit(1);
  }
  
  // 输出统计信息
  console.log(stats.toString({
    colors: true,
    modules: false,
    children: false,
    chunks: false,
    chunkModules: false
  }));
  
  if (stats.hasErrors()) {
    console.log(chalk.red('\n❌ 构建过程中出现错误，请检查上方日志\n'));
    process.exit(1);
  }
  
  console.log(chalk.green('\n✅ 构建完成!\n'));
  
  // 输出构建结果信息
  const buildInfo = stats.toJson();
  
  console.log(chalk.yellow('📊 构建统计:'));
  console.log(`   总大小: ${(buildInfo.assets.reduce((total, asset) => total + asset.size, 0) / 1024).toFixed(2)} KB`);
  console.log(`   文件数量: ${buildInfo.assets.length}`);
  console.log(`   耗时: ${buildInfo.time / 1000} 秒`);
  
  // 构建完成，退出进程
  compiler.close((closeErr) => {
    if (closeErr) {
      console.error(chalk.red('关闭编译器失败:'), closeErr);
    }
  });
}); 